package com.yue.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 功能描述: TODO <br/>
 * 创建时间: 2016/11/1<br/>
 *
 * @author QiuYang
 */
public class BaseZookeeper implements Watcher {

    private ZooKeeper zooKeeper;
    private static final int SESSION_TIME_OUT = 6000;

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    public void connectZookeeper(String host) throws IOException, InterruptedException {
        zooKeeper = new ZooKeeper(host, SESSION_TIME_OUT, this);
        countDownLatch.await();
        System.out.println("zookeeper connect Ok");
    }


    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected){
            System.out.println("watcher received event");
            countDownLatch.countDown();
        }
    }

    // Zookeeper节点， 有生命周期。 节点类型分为：PERSISTENT/EPHEMERAL/SEQUENTIAL.
    public String creatNode(String path, byte[] data) throws KeeperException, InterruptedException {
        return this.zooKeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    public List<String> getChildren(String path) throws KeeperException, InterruptedException {
        return this.zooKeeper.getChildren(path, false);
    }

    public Stat setData(String path, byte[] data, int version) throws KeeperException, InterruptedException {
        return this.zooKeeper.setData(path, data, version);
    }

    public byte[] getData(String path) throws KeeperException, InterruptedException {
        return this.zooKeeper.getData(path, false, null);
    }

    public void deleteNode(String path, int version) throws KeeperException, InterruptedException {
        this.zooKeeper.delete(path, version);
    }

    public void closeConnect() throws InterruptedException {
        if (null != zooKeeper){
            zooKeeper.close();
        }
    }

}
